import { exportExcelWeChat, exportPageTophubRecordWeChat } from '@/services/api/api-tophub-export';
import { CloudDownloadOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  ProColumns,
  ProForm,
  ProFormDateRangePicker,
  ProFormSelect,
  ProTable,
} from '@ant-design/pro-components';
import { useAccess, useModel } from '@umijs/max';
import { Alert, Button, message } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useRef, useState } from 'react';

dayjs.extend(customParseFormat);

const dateFormat = 'YYYY-MM-DD';

interface RecordExportWeChatProps {
  onRefurbish: () => void;
}

const RecordExportWeChat: React.FC<RecordExportWeChatProps> = ({ onRefurbish }) => {
  const access = useAccess();

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  const [loading, setLoading] = useState(false);

  const [createdTimes, setCreatedTimesState] = useState([
    dayjs().add(-7, 'd').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss'),
  ]);

  const actionRef = useRef<ActionType>();

  const [search, setSearch] = useState({
    createdTimes: createdTimes,
    datahubLevelIds: [2000, 3000],
    isConforms: ['0', '1'],
    sorter: {},
  });

  const columns: ProColumns<TophubExporData.ExportRecordSo>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          序号
        </span>
      ),
      dataIndex: 'index',
      align: 'center',
      width: '50px',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          标题
        </span>
      ),
      dataIndex: 'name',
      // align: 'center',
      copyable: true,
      ellipsis: true,
      width: '30%',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          上榜平台
        </span>
      ),
      dataIndex: 'levelName',
      align: 'center',
      width: '80px',
    },

    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          媒体类别
        </span>
      ),
      dataIndex: 'levelId',
      align: 'center',
      width: '80px',
      valueEnum: {
        2000: { text: '市属媒体' },
        3000: { text: '区县媒体' },
      },
    },

    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          阅读量
        </span>
      ),
      sorter: true,
      dataIndex: 'dataReadCount',
      align: 'center',
      render: (dom, entity, index, action) => {
        if (entity.dataReadCount > 100000) {
          return <a>10万+</a>;
        } else {
          return dom;
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          点赞量
        </span>
      ),
      dataIndex: 'dataLikeCount',
      align: 'center',
      sorter: true,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          评论量
        </span>
      ),
      dataIndex: 'dataCommentCount',
      align: 'center',
      sorter: true,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          在看量
        </span>
      ),
      dataIndex: 'dataWatchCount',
      align: 'center',
      sorter: true,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          转发量
        </span>
      ),
      dataIndex: 'dataForwardingCount',
      align: 'center',
      sorter: true,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          综合
        </span>
      ),
      dataIndex: 'dataScoreTotal',
      align: 'center',
      sorter: true,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          收录时间
        </span>
      ),
      dataIndex: 'dataReleaseTime',
      align: 'center',
      width: '100px',
      // render: (dom, entity, index, action) => dayjs(entity.createdTime).format('MM-DD HH:mm'),
    },
  ];

  return (
    <DrawerForm
      title={'导出微信'}
      trigger={<Button type="primary">导出微信</Button>}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        width: 1100,
      }}
      initialValues={{
        createdTimes: [dayjs().add(-7, 'd').startOf('day'), dayjs()],
        isConforms: ['0', '1'],
        datahubLevelIds: ['2000', '3000'],
      }}
      onOpenChange={async (visible) => {
        if (visible) {
        }
      }}
      onValuesChange={(values) => {
        console.log('====', values);
        setSearch({
          ...search,
          ...values,
        });

        actionRef.current?.reloadAndRest();
      }}
      submitter={{
        searchConfig: {
          submitText: (
            <>
              <CloudDownloadOutlined /> 确认导出
            </>
          ),
        },
      }}
      onFinish={async (values) => {
        console.log(values);

        const response = await exportExcelWeChat({
          ...search,
        });
        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
        }
        return false;
      }}
    >
      <ProForm.Group>
        <ProFormDateRangePicker
          name="createdTimes"
          label="日期时间"
          width={250}
          fieldProps={{
            format: (value) => value.format('YYYY-MM-DD'),
            maxDate: dayjs(),
            allowClear: false,
            onChange: (dates, dateStrings) => {
              setCreatedTimesState(dateStrings.map((item) => item + ' 00:00:00'));
            },
          }}
        />
        <ProFormSelect
          name="isConforms"
          label="符合规则"
          valueEnum={{
            '0': '否',
            '1': '是',
          }}
          fieldProps={{
            mode: 'multiple',
          }}
          hidden={true}
          width={'sm'}
          placeholder="请选择热搜范围"
        />
        <ProFormSelect
          name="datahubLevelIds"
          label="媒体类别"
          valueEnum={{
            '2000': '市属媒体',
            '3000': '区县媒体',
          }}
          fieldProps={{
            mode: 'multiple',
          }}
          width={'sm'}
          placeholder="请选择媒体类别"
        />
      </ProForm.Group>
      <ProTable<TophubExporData.ExportRecordSo>
        headerTitle={<Alert message="查询时间比较久" type="warning" showIcon />}
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        request={async (params = {}, sorter) => {
          setSearch({
            ...search,
            sorter: sorter,
          });

          const response = await exportPageTophubRecordWeChat({
            ...params,
            ...search,
            sorter: sorter,
          });

          return {
            data: response.data?.data,
            success: true,
            total: response.data?.total,
          };
        }}
        dateFormatter="id"
        defaultSize={'small'}
        search={false}
        options={{
          density: false,
          setting: false,
        }}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        ghost
      />
    </DrawerForm>
  );
};
export default RecordExportWeChat;
